<template>
  <div class="element-table">
    <div class="el-head">
      <div class="table-left">
        <el-button class="table-button-left" type="primary" @click="handleUpload()">新增</el-button>
        <el-button class="table-button-left" type="primary" @click="handleCategory()">分类管理</el-button>
      </div>
      <div class="table-right">
        <el-input class="table-input-right" placeholder="素材名字" @keyup.enter.native="clickQuery" clearable v-model="fileName"/>
        <el-button class="table-button-right" @click="clickQuery" type="primary">查询</el-button>
      </div>
    </div>
    <div>
      <el-table :data="dataList" border>
        <el-table-column v-slot="scope" label="素材名字" align="center">
          {{ scope.row.fileName }}
        </el-table-column>
        <el-table-column v-slot="scope" label="素材封面" align="center">
          <img :src="imageUtils(windowImg,scope.row.fileCover)" class="tableImg" alt=""/>
        </el-table-column>
        <el-table-column v-slot="scope" label="所属分类" align="center">
          <div v-if="isBlank(scope.row.cateNameList)">暂未设置</div>
          <div style="display: flex;flex-wrap: wrap;" v-else>
            <div v-for="(item,index) in scope.row.cateNameList" :key="index">
              <el-tag style="margin-right: 5px;">{{ item }}</el-tag>
            </div>
          </div>
        </el-table-column>
        <el-table-column v-slot="scope" label="上架时间" align="center">
          {{ scope.row.createDate }}
        </el-table-column>
        <el-table-column v-slot="scope" label="操作" align="center">
          <el-button type="primary" round size="mini" class="table-button-param" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="danger" round size="mini" class="table-button-param" @click="handleDelete(scope.row)">删除</el-button>
        </el-table-column>
      </el-table>
      <el-pagination background :current.sync="pageNo" class="page" layout="total,prev,pager,next" @current-change="change"
        :total="pageTotal" align="center"></el-pagination>
    </div>
    <div>
      <el-dialog title="详情图" width="45%" :visible.sync="imgModal" destroy-on-close close-on-press-escape lock-scroll>
        <img :src="imgName" class="image-details" alt="">
      </el-dialog>
      <el-dialog width="45%" :visible.sync="dataFlag" destroy-on-close :close-on-click-modal="false" close-on-press-escape>
        <div slot="title" style="display: flex;justify-content: center;font-weight: bold;">
          {{ dataTitle }}
        </div>
        <el-form ref="dataDetails" :rules="ruleValidate" :model="dataDetails" label-width="120px" @submit.native.prevent>
          <el-form-item label="素材名字：" prop="fileName">
            <el-input v-model="dataDetails.fileName" :maxlength="20" show-word-limit class="form-input"/>
          </el-form-item>
          <el-form-item label="所属分类：" prop="categoryIdList">
            <el-select v-model="dataDetails.categoryIdList" clearable filterable multiple class="form-input" placeholder="请选择">
              <el-option v-for="(item,index) in materialCategoryList" :value="item.cateId" :label="item.categoryName" :key='index'/>
            </el-select>
          </el-form-item>
          <el-form-item label="素材封面：" prop="avatarUrl">
            <avatar-upload ref="avatarUrl" :img-url.sync="windowImg"/>
          </el-form-item>
          <el-form-item label="素材视频：" prop="videoOneUpload">
            <div style="display: flex;">
              <video-one-upload ref="videoOneUpload" style="width: 100%;" :video-url="windowImg" :size="150"/>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button @click="dataFlag=false">取 消</el-button>
            <el-button type="primary" v-preventReClick @click="handleSubmit('dataDetails')">保存</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import '@/styles/style.scss'
import '@/styles/upload.scss'
import {formatDate, ossPut, isBlank, isFlag, moneyFormat, initCacheData, ossMp4Put} from '@/utils/util'
import appUtils from '@/utils/util'
import {imageUtils} from '@/utils/imageUtil'
import {
  displayPartnerMaterialDelete, displayPartnerMaterialPojoList, displayPartnerMaterialPojoOperation, displayWindowPartnerMaterialCategoryPojoListNoPage
} from '@/api/display'
import {beforeRouteEnterCopy, beforeRouteLeave} from '@/utils/pageUtil'
import CoverUpload from "@/components/Upload/coverUpload";
import AvatarUpload from "@/components/Upload/avatarUpload";
import ruleUtils from "@/utils/ruleUtils";
import VideoOneUpload from "@/components/Upload/videoOneUpload.vue";

export default {
  name: 'displayPartnerMaterialList',
  components: {VideoOneUpload, AvatarUpload, CoverUpload},
  data() {
    const avatarUrlValidator = (rule, value, callback) => {
      if (isBlank(this.$store.state.avatarUpload) && isBlank(this.$store.state.avatarUrl)) {
        return callback(new Error('请上传封面'))
      }
      return callback()
    }
    const videoOneUploadValidator = (rule, value, callback) => {
      if (isBlank(this.$store.state.videoOneUpload)) {
        return callback(new Error('请上传素材视频'))
      }
      return callback()
    }
    return {
      pageNo: 1,
      pageTotal: 0,
      paId: this.$store.state.user.userId,
      seriesId: this.$route.query.seriesId,
      myImage: appUtils.myImage,
      windowImg: appUtils.windowImg,
      fileName: '',
      dataTitle: '',
      imgName: '',
      dataFlag: false,
      dataDetails: {
        fileCover: '',
        categoryId: '',
        categoryIdList: [],
      },
      ruleValidate: {
        fileName: [{
          required: true,
          message: "必填项",
          validator: ruleUtils.nullValidator,
          trigger: "blur",
        }],
        avatarUrl: [{
          required: true,
          validator: avatarUrlValidator,
          trigger: 'blur',
        }],
        videoOneUpload: [{
          required: true,
          validator: videoOneUploadValidator,
          trigger: 'blur',
        }],
      },
      imgModal: false,
      dataList: [],
      materialCategoryList: [],
      routerPage: [],
      dataListCopy: [],
    }
  },
  methods: {
    formatDate,
    ossPut,
    isBlank,
    isFlag,
    moneyFormat,
    imageUtils,
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          const avatarUpload = this.$store.state.avatarUpload
          let cover = this.$store.state.avatarUrl
          if (!isBlank(avatarUpload)) {
            cover = ossPut(avatarUpload, appUtils.windowImg)
          }
          const videoOneUpload = this.$store.state.videoOneUpload
          let videoUrl = videoOneUpload.name
          if (!isBlank(videoOneUpload.raw)) {
            videoUrl = ossMp4Put(videoOneUpload.raw, appUtils.windowImg)
          }
          this.dataDetails.fileUrl = videoUrl
          this.dataDetails.fileCover = cover
          this.dataDetails.paId = this.paId
          this.dataDetails.categoryId = this.dataDetails.categoryIdList.join(',')
          const dataDetailsJson = JSON.stringify(this.dataDetails)
          console.log(dataDetailsJson)
          displayPartnerMaterialPojoOperation(dataDetailsJson).then(res => {
            console.log(res)
            if (isFlag(res.code, 1)) {
              this.$message.success(res.message)
              this.$refs['dataDetails'].resetFields()
              this.dataFlag = false
              setTimeout(() => {
                this.change(this.pageNo)
              }, 200)
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    clickQuery() {
      this.change(1)
    },
    changeSel() {
      this.change(1)
    },
    async change(page) {
      this.pageNo = page
      displayPartnerMaterialPojoList(this.pageNo, this.paId, this.fileName).then(res => {
        console.log(res.data)
        this.dataList = res.data.dataList.map((value, index) => {
          value.createDate = formatDate(new Date(value.createDate), 'yyyy-MM-dd hh:mm')
          return value
        })
        this.dataListCopy = JSON.parse(JSON.stringify(res.data.dataList))
        this.pageTotal = res.data.count
      })
    },
    handleImage(src, name) {
      this.imgName = imageUtils(src, name)
      this.imgModal = true
    },
    handleDelete(param) {
      this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        displayPartnerMaterialDelete(param.fileId).then(res => {
          if (isFlag(res.code, 1)) {
            this.$message.success(res.message)
            this.change(this.pageNo)
          }
        })
      }).catch(_ => {
      });
    },
    handleUpdate(param) {
      this.dataTitle = '素材信息修改'
      this.dataFlag = true
      this.$nextTick(() => {
        this.$refs['dataDetails'].resetFields()
        this.dataDetails = JSON.parse(JSON.stringify(param))
        if (!isBlank(this.dataDetails.categoryId)) {
          this.dataDetails.categoryIdList = this.dataDetails.categoryId.split(',').map(value => {
            return parseInt(value)
          })
        }
        initCacheData()
        if (!isBlank(this.dataDetails.fileCover)) {
          this.$store.state.avatarUrl = this.dataDetails.fileCover
          this.$nextTick(() => {
            this.$refs['avatarUrl'].updateUrl()
          })
        }
        if (!isBlank(this.dataDetails.fileUrl)) {
          this.$store.state.videoOneUpload = {
            url: imageUtils(appUtils.windowImg, this.dataDetails.fileUrl),
            name: this.dataDetails.fileUrl
          }
          this.$store.state.uploadProgress = 0
          this.$nextTick(() => {
            this.$store.state.uploadProgress = 100
          })
        }
      })
    },
    handleUpload() {
      this.dataTitle = '新增素材'
      this.dataFlag = true
      this.$nextTick(() => {
        this.$refs['dataDetails'].resetFields()
        initCacheData()
        let data = {}
        Object.assign(data, this.$options.data.call(this))
        this.dataDetails = data.dataDetails
      })
    },
    handleCategory() {
      this.$router.push({
        name: 'displayPartnerMaterialCategoryList',
      })
    },
    async initData() {
      this.seriesId = this.$route.query.seriesId
      displayWindowPartnerMaterialCategoryPojoListNoPage(this.paId).then((res) => {
        this.materialCategoryList = res.data.dataList
      })
    },
    async initFunctions() {
      if (isFlag(this.$store.state.initDataFlag, true)) {
        await this.initData()
        await this.change(this.pageNo)
      }
    }
  },
  activated() {
    this.initFunctions()
    this.$store.state.initDataFlag = false
    setTimeout(() => {
      this.$store.state.initDataFlag = true
    }, 300);
  },
  beforeRouteLeave(to, from, next) {
    beforeRouteLeave(to, from, next, this.routerPage)
  },
  beforeRouteEnter(to, from, next) {
    //进入页面时会默认执行钩子函数，函数名为change，不可更改默认函数，否则会影响全局
    beforeRouteEnterCopy(to, from, next)
  },
}
</script>
<style scoped>
/deep/ .el-button + .el-button {
  margin-left: 0px;
}

/deep/ .el-table th.el-table__cell {
  user-select: initial;
}
</style>
